//
//  XTVmsController.swift
//  XTMuteOpen
//
//  Created by bushAK on 2024/1/23.
//

import UIKit
import WSProgressHUD
import Alamofire
import WebRTC

class XTVmsController: UIViewController {
    @IBOutlet weak var pageControll: UIPageControl!
    
    @IBOutlet weak var menuBtn: UIButton!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var collectionViewLeftLayout: NSLayoutConstraint!
    
    @IBOutlet weak var collectionViewRightLayout: NSLayoutConstraint!
    
    var modelArray = [XTVmModel]()
    var iceServer = [RTCIceServer]()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册 UICollectionViewCell 类型为 XTVmsCell1Cell 的 Nib
        collectionView.register(UINib(nibName: "XTVmsCell1Cell", bundle: nil), forCellWithReuseIdentifier: "XTVmsCell1Cell")

        // 注册 UICollectionViewCell 类型为 XTVMsCell2 的 Nib
        collectionView.register(UINib(nibName: "XTVMsCell2", bundle: nil), forCellWithReuseIdentifier: "XTVMsCell2")

        setLayout1()
            
        loadVmsArrayData()
        getTurnData()
    }

   
    
    @IBAction func menuClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            setLayout2()
            sender.setImage(UIImage(named: "home_menu2"), for: .selected)
        } else {
            setLayout1()
            sender.setImage(UIImage(named: "home_menu"), for: .normal)

        }
        collectionView.reloadData()
    }

    @IBAction func settingClick(_ sender: Any) {
        // 处理设置按钮点击事件
    }

 
}
extension XTVmsController{
    
    private  func getTurnData()  {
        let token =  XTCommon.getToken()

        let headers:HTTPHeaders = ["Authorization":"Bearer \(token)"]
        let api = XTCommon.get_api_get_turns()
        Alamofire.AF.request(api, method: .get, headers: headers).responseJSON { (response) in
            switch response.result {
            case .success(let json):
                guard let turns = json  as? [[String:Any]] else {
                    return
                }
               var array = [XTTurnsModel]()
                var urlArray = [String]()
                for turn in turns {
                    let model  = XTTurnsModel()
                    model.credential = turn["credential"] as? String ?? ""
                    model.urls = turn["urls"] as? String ?? ""
                    model.username = turn["username"] as? String ?? ""
                    array.append(model)
                    urlArray.append(model.urls)
                }
                
                let server = RTCIceServer.init(urlStrings: urlArray, username: array.first!.username, credential: array.first!.credential ,tlsCertPolicy: .insecureNoCheck)
                self.iceServer.removeAll()
                self.iceServer.append(server)
                break
            case .failure(_):
       
                break
            }
        }
    }
    
    
   private func loadVmsArrayData()  {
       WSProgressHUD.show()
       // token
       let token = XTCommon.getToken()
       if token.count > 5 {
           let headers:HTTPHeaders = ["Authorization":"Bearer \(token)"]
       
           
           Alamofire.AF.request(XTCommon.get_api_list_vms(), method: .get, parameters: ["platform":"1"],headers: headers).responseJSON { (response) in
               WSProgressHUD.dismiss()
               switch response.result {
               case .success(let json):
                   guard let json  = json as? [String:Any],
                         let vms = json["vms"] as? [[String:Any]] else {
 
                       return
                   }
                   print(json)
                   if vms.count > 0 {
                       self.modelArray.removeAll()
                       for data in vms {
                           guard let data = data as? [String : Any] else {
                               return
                           } //
                           var model = XTVmModel()
 
                           let alloced = data["alloced"] as? Bool ?? false
                           let paused = data["paused"] as? Bool ?? false
                           let connected = data["connected"] as? Bool ?? false
                           let isAuthed = data["isAuthed"] as? Bool ?? false
                           let canControl = data["canControl"] as? Bool ?? false
 
                           let level = data["level"] as? String ?? ""
                           let type = data["type"] as? String ?? ""
                           let sid = data["sid"] as? String ?? ""
                           let ip = data["ip"] as? String ?? ""
                           let expire_time = data["expire_time"] as? String ?? ""
                           let group = data["group"] as? String ?? ""
                           let id = data["id"] as? Int ?? 0
                           let license_id = data["license_id"] as? Int ?? 0

                           let room = data["room"] as? String ?? ""
                           let name = data["name"] as? String ?? ""
                           model.alloced = alloced
                           model.canControl = canControl
                           model.connected = connected
                           model.expire_time = expire_time
                           model.group = group
                           model.id = id
                           model.ip = ip
                           model.isAuthed = isAuthed
                           model.level = level
                           model.license_id = license_id
                           model.name = name
                           model.paused = paused
                           model.room = room
                           model.sid = sid
                           model.type = type
                           self.modelArray.append(model)
                       }
                       
                       self.collectionView.reloadData()
                       self.pageControll.numberOfPages = vms.count
                       self.pageControll.currentPage = 0
                   }else{
                       self.pageControll.numberOfPages = 0
                   }
                   break
               case .failure(_):
                   WSProgressHUD.showError(withStatus: "数据加载失败")
 
                   break
               }
           }
           
       }
       
    }
}

extension XTVmsController{
    private func setLayout1() {
        let layout = UICollectionViewFlowLayout()
        let padding: CGFloat = 14.0
        let W = (UIScreen.main.bounds.size.width - 3 * padding - 3) / 2.0
        let H = W * 15 / 8.5
        layout.itemSize = CGSize(width: W, height: H)
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = padding
        layout.minimumLineSpacing = padding

        collectionView.collectionViewLayout = layout
        collectionView.contentInset = UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
        pageControll.isHidden = true
        collectionView.isPagingEnabled = false
        collectionViewLeftLayout.constant = 0
        collectionViewRightLayout.constant = 0
        collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        collectionView.bounces = true
    }
    private func setLayout2() {
        let layout = UICollectionViewFlowLayout()

        let H = collectionView.frame.size.height * 0.8
        let W = H * 0.6

        layout.itemSize = CGSize(width: W, height: H)
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0

        collectionView.collectionViewLayout = layout

        let contentInset = (collectionView.frame.size.height - H) * 0.5
        collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: contentInset, right: 0)
        pageControll.isHidden = false
        collectionView.isPagingEnabled = true

        let leftP = (UIScreen.main.bounds.size.width - W) * 0.5
        collectionViewLeftLayout.constant = leftP
        collectionViewRightLayout.constant = leftP
        collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        collectionView.bounces = false
        pageControll.currentPage = 0
    }
}

extension XTVmsController : UICollectionViewDelegate,UICollectionViewDataSource{

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modelArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if menuBtn.isSelected {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XTVMsCell2", for: indexPath) as! XTVMsCell2
            cell.model = modelArray[indexPath.row]
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XTVmsCell1Cell", for: indexPath) as! XTVmsCell1Cell
            cell.model = modelArray[indexPath.row]

            return cell
        }
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        if menuBtn.isSelected {
            let padding = scrollView.contentOffset.x / collectionView.frame.size.width
            print(Int(padding))
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if menuBtn.isSelected {
            let padding = scrollView.contentOffset.x / collectionView.frame.size.width
            pageControll.currentPage = Int(padding)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = XTOperationViewController()
        vc.vmModel = modelArray[indexPath.item]
        vc.iceTurnArray = iceServer
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)
    }
}
